package com.lam.framework.mybatis;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.lam.common.components.redis.RedisUtil;
import com.lam.common.utils.BeanUtil;
import com.lam.common.utils.IpUtils;
import com.lam.common.utils.JsonUtil;
import com.lam.common.utils.SpringUtils;
import com.lam.common.utils.StringUtils;

/**
 * @author lam
 *
 */
public class MybatisUtil {

    private static final Logger logger = LoggerFactory.getLogger(MybatisUtil.class);
    
    private MybatisUtil(){
		throw new IllegalStateException("Utility class");
	}

    public static <T> T transfer(Environment env, T bean, String prefix){

        prefix = StringUtils.isNotBlank(prefix) ? prefix + "." : "";

        List<Field> fields = BeanUtil.getBusinessFields(bean.getClass());
        String val;
        for(Field fd:fields){
            val = env.getProperty(prefix + fd.getName());
            if(val != null){
            	try {
            		// 获得set方法
        			Method setMethod = new PropertyDescriptor(fd.getName(), bean.getClass()).getWriteMethod();
        			if(setMethod != null){
        				setMethod.invoke(bean, val);
        			}
        		} catch (Exception e) {
        			logger.debug(e.getMessage(), e);
        		}
            }
        }
        return bean;
    }
    
    public static String scanTypeAliasesPackage(String typeAliasesPackage) {
    	if(StringUtils.isBlank(typeAliasesPackage)) {
    		return null;
    	}
    	logger.info("Mybatis开始扫描TypeAliasesPackage...");
    	Set<String> result = new HashSet<>();
    	for (String pt : typeAliasesPackage.split(",")) {
    		result.addAll(SpringUtils.scanPackage(pt.trim()));
		}
    	if (result.size() > 0) {
			return String.join(",", result);
		}
		throw new RuntimeException("mybatis typeAliasesPackage 路径扫描错误,参数typeAliasesPackage:" + typeAliasesPackage + "未找到任何包");
	}
    
    /**
     * 初始化mybaitsPlus的workerId和DatacenterId
     */
    public static void initIdWorker() {
		
		long idNum = getIdWorkerNum();
		IdWorker.initSequence(idNum, idNum);
    }
    
    public static int getIdWorkerNum() {
    	int idNum = 0;
		String key = "";
		String ip = IpUtils.getHostIp();
		do{
			idNum++;
			key = String.format("MybaitsPlus.workerId:%s", idNum);
		}while(RedisUtil.hasKey(key) && !StringUtils.equals(ip, JsonUtil.toString(RedisUtil.get(key))));
		RedisUtil.set(key, ip);
		return idNum;
    }
    
}